<template>
  <div>
    <!-- 实验信息 -->
    <h2>实验信息<span class="comeback" @click="comeback">/返回</span></h2>
    <!-- :rules="registerRule" -->
    <Form :model="experimentMsg"   ref="registerForm">
        <FormItem prop="username" label="实验名称">
            <Input type="text" v-model="experimentMsg.name" :disabled="noeditExperimentMsg"></Input>
        </FormItem>
        <FormItem prop="password" label="实验类型">
            <Input v-model="experimentMsg.type" :disabled="noeditExperimentMsg"></Input>
        </FormItem>
        <FormItem prop="nickName" label="状态">
            <!-- <Input v-model="experimentMsg.status"></Input> -->
            <i-switch v-model="experimentMsg.status" :disabled="noeditExperimentMsg"></i-switch>  
        </FormItem>
        <FormItem prop="phone" label="内容">
            <!-- <Input v-model="experimentMsg.content"></Input> -->
            <Input v-model="experimentMsg.content" :rows="8" type="textarea" :disabled="noeditExperimentMsg"></Input>
        </FormItem>
        <FormItem prop="email" label="">
            <!-- <Input v-model="experimentMsg.word" :disabled="noeditExperimentMsg"></Input> -->
            <Upload 
              ref="upload"
              action="http://laboratory101.oss-cn-hangzhou.aliyuncs.com" 
              :show-upload-list="false"
              :before-upload="handleBeforeUpload"
              :on-progress="handleProgress"
              :on-success="handleSuccess"
              :data="dataObj"
              :on-remove="removeFile"
              :on-preview="previewFile"
              >
              <!-- type="ghost" icon="ios-cloud-upload-outline" -->
              <Button  type="info" icon="ios-cloud-upload-outline" :disabled = "noUpload">上传文件</Button>
            </Upload>
             
            <div class="wait-flag" v-if="waiting">
              <Progress :percent="percent" status="active"></Progress>
              文件上传中...
            </div>
            <div v-if="experimentMsg.word" class="file">
              <span class="iconfont icon-wenjian"></span>
                <!-- <a :href="experimentMsg.word" :download="curFile">{{curFile}}</a> -->
                <span class="openfile" @click="openFile">{{curFile}}</span>
              <span class="iconfont icon-shanchu" @click="delFile"></span>
            </div>
            
        </FormItem>
        <FormItem>
            <Button type="primary" @click="edit" :disabled="noEdit">编辑</Button>
            <Button type="primary" @click="canceledit" :disabled="noSubmit">撤销</Button>
            <Button type="primary" @click="save" :disabled="noSubmit">保存</Button>
        </FormItem>
    </Form>    

    <h2>样品信息</h2>
      <Button type="success" @click="$router.push({path:'/admin/addrecord',query:{experimentMsg:experimentMsg}})">添加</Button>
                   
      <Table border ref="table" :columns="columns" :data="recordList">
        <template slot-scope="{ index }" slot="index">
            {{index + 1}}
        </template>
        <template slot-scope="{ row, index }" slot="action">
            <Button type="primary" size="small" style="margin-right: 5px" @click="editRecord(row,index)">编辑</Button>
            <Button type="error" size="small" @click="removeRecord(row,index)">删除</Button>
        </template>
        <template slot-scope="{ row }" slot="createTime">
            {{row.createTime | moment}}
        </template>
        <template slot-scope="{ row }" slot="updateTime">
            {{row.updateTime | moment}}
        </template>
        <template slot-scope="{ row }" slot="status">
            <i-switch v-model="row.status" :disabled="true"></i-switch>  
        </template>
      </Table>
      <!-- 分页 -->
      <Page :total="total" :page-size="params.limit" @on-change="changPage"  v-if="update"></Page>
  
      <!-- 删除实验 -->
      <Modal v-model="showDelete" @on-cancel="cancel">
        <p slot="header" style="color:#f60;text-align:center">
            <Icon type="ios-information-circle"></Icon>
            <span>Delete {{curRecord.recordName}}</span>
        </p>
        <div style="text-align:center">
            <p>该删除操作无法撤销</p>
            <p>确定删除？</p>
        </div>
        <div slot="footer">
            <Button type="error" size="large" long :loading="modal_loading" @click="delRecord">Delete</Button>
        </div>
      </Modal>    
  </div>
</template>

<script>
import {getUUID} from '@/utils/index.js'
export default {
  data(){
    return{
      //实验信息
      experimentId:'',
      experimentMsg:{
        content: '',
        id: '',
        name: '',
        status: '',
        type: '',
        userId: '',
        word: ''
      },
      noeditExperimentMsg:true,
      userid:'',
      columns: [
        {
            title: '#',
            slot:'index',
            width:'60px',
            align: 'center'
        },
        // {
        //     title: 'ID',
        //     key: 'recordId',
        //     align: 'center'
        // },
        {
            title: '样品编号',
            key: 'recordName',
            align: 'center'
        },
        {
            title: '基底类型',
            key: 'type',
            align: 'center'
        },
        {
            title: '实验材料',
            key: 'material',
            align: 'center'
        },
        {
            title: '反应条件',
            key: 'conditions',
            align: 'center'
        },
        {
            title: '样品增重',
            key: 'weight',
            align: 'center'
        },
        {
            title: '创建时间',
            key: 'createdTime',
            slot: 'createTime',
            align: 'center'
        },
        {
            title: '更新时间',
            key: 'updatedTime',
            align: 'center',
            slot: 'updateTime'
        },
        {
            title: '状态',
            key: 'status',
            align: 'center',
            slot:'status'
        },
        {
            title: '操作',
            slot:'action',
            align: 'center'
        }
      ],
      recordList: [  
        
      ],
      //分页配置
      total:0,
      params:{
        page:1,
        limit:5,
        key:''
      },
      searchKey:'',   
      update:true,
      // 删除框配置
      showDelete:false,
      curRecord:'',
      modal_loading: false,  
      //1.文件上传所需信息
      dataObj:{
        policy:'',
        signature:'',
        ossaccessKeyId:'',
        key:'',
        dir:'',
        host:''
      },   
      //是否允许上传
      // noUpload:true,
      noEdit:false,
      noSubmit:true,
      defaultFile:[],
      waiting:false,
      percent:0
    }
  },
  computed:{
    curFile(){
      if(this.experimentMsg.word){
        let index = this.experimentMsg.word.lastIndexOf('_')
        return this.experimentMsg.word.slice(index + 1)
      }
    },
    noUpload(){
      //不能上传的时候返回true
      //已经有文件了
      if(this.experimentMsg.word){
        return true
      }
      //未处于编辑状态
      if(!this.noEdit){
        return true
      }
      return false
    }
  },
  created(){
    let usermsg = JSON.parse(window.sessionStorage.getItem('usermsg'))
    this.userid = usermsg.id
    this.experimentId = this.$route.query.experimentMsg.id 
    this.getExperiment(this.experimentId)
    this.getRecordList()
  },
  mounted(){
    // this.$refs.upload.fileList.push({
    //   status:"finished",
    //   src:this.experimentMsg.word
    // })
    // console.log(this.$refs.upload.fileList)
  },
  methods:{
    //获取实验数据
    async getExperiment(id){
      const {data:res}  = await this.$axios.get('/experiment/message/' + id)
      this.experimentMsg = res.data  
      console.log(this.$refs.upload.fileList)
      this.defaultFile.push({
        url:this.experimentMsg.word
      })
    },
    //获取编号数据
    async getRecordList(){
      const {data:res}  = await this.$axios.get('/record/list/' + this.experimentId,{
        params:this.params
      })
      // console.log(res)
      this.recordList = res.page.list
      this.total = res.page.totalCount
    },
    // 分页页数改变
    changPage(page){
      // console.log(page)
      this.params.page = page
      this.getRecordList(this.params)
    },
    search(){
      this.params.key = this.searchKey.trim()
      this.getRecordList(this.params)
    },
    // 编辑保存实验信息
    edit(){
      this.noeditExperimentMsg = false
      this.noSubmit = false
      this.noEdit = true
    },
    async save(){
      const {data:res} = await this.$axios.post('/experiment/update',this.experimentMsg)
      if(res.status !== 200){
        this.$Message.info(res.msg)
        return
      }
      this.$Message.info(res.msg)
      this.noeditExperimentMsg = true
      this.noSubmit = true
      this.noEdit = false
    },
    canceledit(){
      this.getExperiment(this.experimentId)
    },
    //编辑样品
    editRecord(row,index){
      this.$router.push({
        path:'/admin/editrecord',
        query:{
          recordMsg:row,
          experimentMsg:this.experimentMsg
        }
      })
      // console.log(row,index)
    },
    //删除样品
    removeRecord(row,index){
      this.curRecord = row
      this.showDelete = true
    },
    async delRecord(){
      this.modal_loading = true
      const {data:res} = await this.$axios.post('/record/delete/' + this.curRecord.recordId)
      //重新获取数据
      this.params.page = 1
      this.getRecordList(this.params) 
	    // 移除组件(组件强制刷新)
	    this.update = false
	    // 在组件移除后，重新渲染组件
	    // this.$nextTick可实现在DOM 状态更新后，执行传入的方法。
	    this.$nextTick(() => {
	        this.update = true
	    })  
      this.modal_loading = false
      this.showDelete = false
      this.curRecord = {}   
      this.$Message.info(res.msg)
    },
    cancel(){
      this.curRecord = {}
    },   
    // 文件上传
    //请求后端获取阿里云信息
    async handleBeforeUpload () {
      this.waiting = true
      await this.beforeUpload()
    },
    async beforeUpload(){
      const {data:response} = await this.$axios.post('/oss/policy')
      this.dataObj.policy = response.data.policy;
      this.dataObj.signature = response.data.signature;
      this.dataObj.ossaccessKeyId = response.data.accessid;
      this.dataObj.key = response.data.dir + getUUID() + '_${filename}';
      this.dataObj.dir = response.data.dir;
      this.dataObj.host = response.data.host;  
    }, 
    handleProgress(e){
      // console.log(e)
      this.percent = Math.floor(e.percent)
    },
    handleSuccess (res, file) {
      this.experimentMsg.word = this.dataObj.host + '/' + this.dataObj.key.replace("${filename}",file.name) 
      this.waiting = false
      this.percent = 0
      // console.log(file)
      // this.percent = 100
      console.log(this.$refs.upload)
    },
    removeFile(){

    },
    previewFile(){
      window.location.href = this.experimentMsg.word
    },
    delFile(){
      if(!this.noEdit){
        return
      }
      this.experimentMsg.word = ''
    },
    openFile(){
      window.location.href = this.experimentMsg.word
    },
    //返回实验列表
    comeback() {
      this.$router.push('/admin/experiment')
    }
  }
}
</script>

<style scoped>
  .ivu-btn-success{
    margin:1vh 1vw;
  }
  .ivu-page{
    margin-top:20px;
    text-align:center
  }
  .ivu-form{
    width:30%;
    margin-left:1vw
  }
  h2{
    margin:1vw 2vh
  }
  /* 图标 */
  .icon-shanchu{
    cursor:pointer;
    vertical-align: bottom;
    font-size:20px;
  }
  .file{
    margin-top:10px;
  }
  .openfile{
    cursor:pointer;
  }
  .wait-flag {
    margin-top:10px
  }
  .comeback {
    cursor:pointer;
  }
  /* pad样式  */
  @media screen and (max-width:960px) and (min-width:750px){ 
    .ivu-form{
      width:40%
    }
  }   
  /* 手机端样式 */
  @media screen and (max-width:750px){ 
    .ivu-form{
      width:80%
    }   
  } 
</style>